// set key and secret
var key = 'yourkey'
var secret = 'yoursecret'
var sandbox = true

var express = require('express')
var fs = require('fs')
var _ = require('lodash')
var app = express();
var http = require('http')
http.createServer(app).listen(3001, function() {
  console.log('Http server listening on port ' + 3001);
})

// get
app.get('/', function(req, res) {
  res.send(JSON.stringify({
    message: 'ok'
  }));
  res.end();
})

function getUserId(resText) {
  var reg = /\"userId\":(\s*|\s+)\d+/;
  var arr = resText.match(reg);
  var userId = arr[0].split(":")[1].trim();
  return userId;
}

app.post('/', function(req, res) {
  // 由于userId长度为17位，且类型为long，通过截取字符串方式获取userId
  var buffers = [];
  req.on('data', function(chunk) {
    buffers.push(chunk);
  })
  req.on('end', function() {
    var buffer = Buffer.concat(buffers);
    bufferStr = buffer.toString('utf-8');
    var userId = getUserId(bufferStr)
    var body = JSON.parse(bufferStr);
    var message = JSON.parse(body.message);
    body.userId = userId;
    var getSignature = require('./utils').getSignature;
    var obj = _.clone(body)
    delete obj.signature;

    // 第二个参数为secret
    if (getSignature(obj, secret) !== body.signature) {
      console.log('signature is not valid')
    } else {
      res.send(JSON.stringify({
        message: 'ok'
      }));
      if (body.type === 10) {
        confirmOrder(userId, message.id)
          .then(result => {
            console.log('confirm')
          })
          .catch(e => {
            console.log('error', e)
          })
      }
    }
  })
})

function confirmOrder(userId, orderId) {
  var eleme = require('eleme-openapi-sdk');
  var Config = eleme.Config;
  var RpcClient = eleme.RpcClient;
  var options = {
    key: key,
    secret: secret,
    sandbox: sandbox,
  }
  var config = new Config(options);
  var id2token = fs.readFileSync('./token.json')
  var id2token = JSON.parse(id2token)
  var token = JSON.parse(id2token[userId]).access_token
  var rpc_client = new RpcClient(token, config);
  var orderService = new eleme.OrderService(rpc_client)
  return orderService.confirmOrder(orderId)
}

